
#include <sys/types.h>
#include <sys/signal.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/wait.h>
#include <sys/errno.h>
#include <netinet/in.h>

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "config.h"

void MakePackage(unsigned int Type, unsigned int Device, unsigned int Command, unsigned int Data);
int DeviceOperation(unsigned int Device, unsigned int Command, unsigned int *Data);

unsigned int buffer[64];

int main(int argc, char *argv[]) {

	int client_sockfd;  
	int len;  
	struct sockaddr_in remote_addr;
	unsigned int recv_buf[64];
	unsigned int send_buf[64];
	int recv_cnt;
	int send_cnt;
	int result;

	result = init_device();
	if (result == -1) {
		printf("Device Initial failed!\n");
		return 0;
	}else{
		printf("Device Ready.\n");
	}

	memset(&remote_addr,0,sizeof(remote_addr));
	remote_addr.sin_family=AF_INET;
	remote_addr.sin_addr.s_addr=inet_addr("198.74.113.200");
	remote_addr.sin_port=htons(8001);
	  
	if((client_sockfd=socket(PF_INET,SOCK_STREAM,0))<0)  
	{  
		    perror("socket");  
			    return 1;  
	}  
	  
	if(connect(client_sockfd,(struct sockaddr *)&remote_addr,sizeof(struct sockaddr))<0)  
	{  
		    perror("connect");  
			    return 1;  
	}  
	printf("connected to server/n");  

	MakePackage(0xC0000001, 0, 0, 0);
	send_cnt = write(client_sockfd, buffer, 256);
	if (send_cnt < 0)
	  errexit("send package to Server, %s\n", strerror(errno));

	while(1) {
		recv_cnt = read(client_sockfd, buffer, 256);
		if (recv_cnt > 6) {
			if (recv_buf[0] == 0xAAAAAAAA) {
				printf("package received.\n");
				if (recv_buf[1] == 0xA0000002) {
					result = DeviceOperation(recv_buf[2], recv_buf[3], recv_buf+4);
					if (result) {
						MakePackage(0xC0000002, recv_buf[2], recv_buf[3], recv_buf[4]);
						while(send_cnt = write(client_sockfd, buffer, 256)) {
							if (send_cnt < 0)
							  errexit("send package to Server, %s\n", strerror(errno));
						}
					}
				}
			}
		}
	}
}

void MakePackage(unsigned int Type, unsigned int Device, unsigned int Command, unsigned int Data) {

	memset(buffer, sizeof(buffer), 0);
	buffer[0] = 0xAAAAAAAA;
	buffer[1] = Type;
	buffer[2] = Device;
	buffer[3] = Command;
	buffer[4] = Data;
	buffer[63] = 0xFFFFFFFF;

}

